package com.ziyear.servlet;

import com.ziyear.common.util.JDBCUtil;
import com.ziyear.common.util.TrainUtils;
import com.ziyear.domain.Prep;
import com.ziyear.domain.Train;
import com.ziyear.service.PrepService;
import com.ziyear.service.TrainSeatService;
import com.ziyear.service.TrainService;
import com.ziyear.service.impl.PrepServiceImpl;
import com.ziyear.service.impl.TrainSeatServiceImpl;
import com.ziyear.service.impl.TrainServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 功能描述 : 会员 改签业务
 *
 * @author Ziyear
 */
public class ChangePrepServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        try {
            JDBCUtil.startTransaction();
            // prepId这是从UpdatePrepServlet过来的，实现改签业务，
            Integer prepId = (Integer) request.getAttribute("prepId");

            PrepService prepService = new PrepServiceImpl();
            TrainService trainService = new TrainServiceImpl();
            // 将订单信息中的trainID先拉取出来，下面更改车次座位数需要
            Prep prep = prepService.getById(prepId);
            Integer trainId = prep.getTrainId();

            // 释放座位
            TrainSeatService trainSeatService = new TrainSeatServiceImpl();
            trainSeatService.freed(prep.getTrainSeatId());

            // 删除这个订单
            int recordNumber = 0;
            recordNumber = prepService.delete(prepId);

            if (recordNumber == 0) {
                throw new RuntimeException("更新数据库失败改签失败！");
            }
            // 座位数+1
            Train train = trainService.getById(trainId);
            TrainUtils.increaseNumber(train, prep.getSeatType());
            trainService.update(train);

            // 将改签开始的信息存到session，告知BookingServlet这是改签
            request.getSession().setAttribute("changePrep", "true");

            // 跳转
            out.write("<script>alert('请您选择新的车次！');" +
                    "window.location.href='GetByStartEndStationServlet'</script>");

            JDBCUtil.commit();
        } catch (Exception e) {
            e.printStackTrace();
            JDBCUtil.commit();
            out.write("<script>alert('很抱歉,改签失败！');" +
                    "window.location.href='MyPrepServlet'</script>");
        }

    }


}
